package com.study01.lesson02_TCP;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemo02 {
        public static void main(String[] args) {
            Socket socket =null;
            OutputStream os = null;
            //1.要知道服务器地址
            try {
                    InetAddress serverIp = InetAddress.getByName("127.0.0.1");
                    //2.端口号
                    int port = 9000;
                    socket = new Socket(serverIp,port);
                    //3发送消息
                    os = socket.getOutputStream();
                    //读取文件
                    FileInputStream fis =new FileInputStream(new File("twq.jpg"));
                  //写出文件
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }

                //通知服务器，我已经结束了
                socket.shutdownOutput();//我已经传输完
                //确定服务器接收完毕了，才能断开连接
                InputStream inputStream = socket.getInputStream();
                //String byte[]
                ByteArrayOutputStream baos =new ByteArrayOutputStream();

                byte[] buffer2 = new byte[2014];
                int len2;
                while ((len2 = inputStream.read(buffer2)) != -1) {
                    baos.write(buffer2, 0, len2);
                }
                System.out.println(baos.toString());
                baos.close();
                inputStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {


                if (os!=null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }


